﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OOAD_Project_Engine.Foundation.Interfaces;
using Microsoft.Xna.Framework;
using OOAD_Project_Engine.Foundation;

namespace OOAD_Project_Engine.Domain.Components
{
    public sealed class Transform : EntityComponent, ITransformProperty
    {
        public Transform()
        {
            Scale = new Vector2(1);
            Position = new Vector2(0);
        }
        [ComponentProperty(Serializable = true)]
        public Microsoft.Xna.Framework.Vector2 Scale { get; set; }

        [ComponentProperty(Serializable = true)]
        public Microsoft.Xna.Framework.Vector2 Position { get; set; }

        [ComponentProperty(Serializable = true)]
        public float Rotation { get; set; }

        public override void Update(Microsoft.Xna.Framework.GameTime gameTime)
        {
            base.Update(gameTime);

            if (Owner.Parent == null)
            {
                World = ProjectionMatrix(this);
            }
            else
            {
                if (Owner.Parent.Contains<Transform>())
                {
                    Transform parentTransform = Owner.Parent.Find<Transform>();
                    World = ProjectionMatrix(this) * parentTransform.World;
                }
            }
        }

        Matrix ProjectionMatrix(ITransformProperty entity)
        {
            float radians = entity.Rotation;
            Vector2 entityPos = entity.Position;
            Vector2 scale = entity.Scale;
            return CoordinateHelper.ProjectionMatrix(radians, entityPos, Vector2.Zero, scale);
        }

        Matrix UnprojectionMatrix(ITransformProperty entity)
        {
            float radians = entity.Rotation;
            Vector2 entityPos = entity.Position;
            //Vector2 orginSize = entity.Size * entity.Origin;
            Vector2 scale = entity.Scale;
            return CoordinateHelper.UnprojectionMatrix(radians, entityPos, Vector2.Zero, scale);
        }

        public Microsoft.Xna.Framework.Matrix World
        {
            get;
            private set;
        }

        public override object Clone()
        {
            Transform t = new Transform();
            t.Position = Position;
            t.Rotation = Rotation;
            t.Scale = Scale;
            return t;
        }
    }
}
